/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajamas.example.scheduler.controller;

import org.pajamas.example.scheduler.job.KeyLoggingJob;
import org.pajamas.example.scheduler.vo.SchedulingVo;
import org.pajamas.starter.core.vo.ResultVo;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author william
 * @since 2024/6/2
 */
@RequestMapping("/trigger")
@RestController
public class TriggerController {
    @Autowired
    private Scheduler scheduler;

    /**
     * schedule job with trigger, and store the both
     * TODO jobDetail stored successfully but trigger
     *
     * @param vo vo
     * @return org.pajamas.starter.core.vo.ResultVo
     * @author william
     * @since 2024/6/10
     */
    @PutMapping("put")
    public ResultVo put(@RequestBody SchedulingVo vo) throws SchedulerException {
        JobDetail job = JobBuilder
                .newJob(KeyLoggingJob.class)
                .withIdentity(vo.getJobKeyName(), vo.getJobKeyGroup())
                .storeDurably()
                .build();

        Trigger trigger = TriggerBuilder
                .newTrigger()
                .withIdentity(vo.getTriggerKeyName(), vo.getTriggerKeyGroup())
                .forJob(vo.getJobKeyName(), vo.getJobKeyGroup())
                .startNow()
                .endAt(new Date(new Date().getTime() + vo.getDuration()))
                .withSchedule(CronScheduleBuilder.cronSchedule(vo.getCron()))
                .usingJobData(vo.getJobData())
                .build();
        Date date = this.scheduler.scheduleJob(job, trigger);
        return ResultVo.builder().payload(date).build();
    }
}
